export class Dep {
  constructor() {
    this.subscribers = new Set();
  }
  depend() {
    // 这里之所以要这么写，是因为手动调用对象的属性时(触发getter)防止再次不必要的收集依赖
    if (activeUpdate) {
      this.subscribers.add(activeUpdate);
    }
  }
  notify() {
    this.subscribers.forEach(sub => sub());
  }
}

export function observe(obj) {
  Object.keys(obj).forEach((key) => {
    let internalValue = obj[key];
    if (typeof internalValue === "object") {
      observe(internalValue);
    }
    const dep = new Dep();
    Object.defineProperty(obj, key, {
      get() {
        dep.depend();
        return internalValue;
      },
      set(newVal) {
        const changed = internalValue !== newVal;
        internalValue = newVal;
        if (changed) {
          dep.notify();
        }
      },
    });
  });
  // return obj;
}

let activeUpdate = null;

export function autorun(update) {
  // 这里之所以要这么写，是因为手动调用对象的属性时(触发getter)防止再次不必要的收集依赖
  const wrappedUpdate = () => {
    activeUpdate = wrappedUpdate;
    update(); // 执行了update，读取了state的getter触发依赖收集
    activeUpdate = null;
  };
  wrappedUpdate();
}
